<template>
  <el-container>
    <el-main>
      <el-row class="function-button">
        <el-button type="success" size="small" round @click="refresh()"
          >刷新按钮</el-button
        >
        <el-collapse accordion class="accordion">
          <el-collapse-item>
            <template slot="title">
              筛选<i class="header-icon el-icon-info"></i>
            </template>
            <div>
              <el-button
                class="queryBtn"
                round
                type="success"
                style="margin-left: 10px"
                @click="queryByCondition"
                >查询</el-button
              >
              <el-button
                class="queryBtn"
                round
                style="margin-left: 10px"
                type="warning"
                @click="resetResumeQueryParams"
                >重置</el-button
              >
            </div>

            <el-input
              style="width: 20%; margin-left: 40px"
              v-model="resumeQueryParam.name"
              placeholder="请输入学生名称"
            ></el-input>
            <el-input
              style="width: 20%; margin-left: 40px"
              v-model="resumeQueryParam.studentId"
              placeholder="请输入学号"
            ></el-input>
            <el-select
              style="width: 20%; margin-left: 40px"
              v-model="resumeQueryParam.jobCategoryId"
              placeholder="请输入岗位类别"
              filterable
            >
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              style="width: 20%; margin-left: 40px"
              v-model="resumeQueryParam.expectedPosition"
              placeholder="请选择岗位名称"
              filterable
            >
              <el-option
                v-for="item in jobNameAndIdList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-input
              style="width: 20%; margin-left: 40px"
              placeholder="输入薪资范围,如(3k-5k)"
              size="samll"
              prefix-icon="el-icon-search"
              v-model="resumeQueryParam.monthSalary"
            >
            </el-input>
            <!-- 城市选择 -->
            <el-cascader
              size="large"
              style="width: 20%; margin-left: 40px"
              :options="regionData"
              v-model="resumeQueryParam.addressId"
              @change="handleChangeAtQuerying(resumeQueryParam.addressId)"
              :props="{ checkStrictly: true }"
              placeholder="工作地点(省 / 市 / 区)"
            >
            </el-cascader>
            <el-date-picker
              style="width: 20%; margin-left: 40px"
              type="datetimerange"
              v-model="resumeQueryParam.updateTime"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-collapse-item>
        </el-collapse>
      </el-row>
      <template>
        <el-table
          ref="resumeTable"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          v-loading="loading"
          :data="resumes"
          fit
          max-height="100vh"
          size="medium "
          class="tableStyle"
          highlight-current-row
          row-key="id"
          tooltip-effect="dark"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="实习经验">
                  <span>{{ props.row.internshipExperience || '无' }}</span>
                </el-form-item>
                <el-form-item label="项目经验">
                  <span>{{ props.row.projectExperience || '无' }}</span>
                </el-form-item>
                <el-form-item label="工作经历">
                  <span>{{ props.row.experience || '无' }}</span>
                </el-form-item>
                <el-form-item label="技能">
                  <span>{{ props.row.skill || '无' }}</span>
                </el-form-item>
                <el-form-item label="证书">
                  <span>{{ props.row.certificate || '无' }}</span>
                </el-form-item>
                <el-form-item label="自我评价">
                  <span>{{ props.row.selfEvaluation || '无' }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发布时间" width="100">
            <template slot-scope="scope">
              {{ scope.row.createTime | dateFMT }}
            </template>
          </el-table-column>
          <el-table-column prop="studentId" label="学号" width="100">
          </el-table-column>
          <el-table-column prop="major" label="专业">
            <template slot-scope="scope">
              <span>{{
                majorListForIdAndName.find(
                  (item) => item.id === scope.row.major
                ).name || ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="100">
          </el-table-column>
          <el-table-column prop="birthday" label="年龄" width="200">
          </el-table-column>
          <el-table-column prop="sex" label="性别" width="100">
            <template slot-scope="scope">
              {{ scope.row.sex === 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号码" width="100">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="100">
          </el-table-column>
          <el-table-column prop="expectedCity" label="期望工作城市" width="200">
          </el-table-column>
          <el-table-column
            prop="expectedPositionCategoryName"
            label="期望职位类别"
            width="200"
          >
          </el-table-column>
          <el-table-column
            prop="expectedPositionName"
            label="期望职位"
            width="200"
          >
          </el-table-column>
          <el-table-column prop="expectedSalary" label="期望薪资" width="200">
            <template slot-scope="scope">
              <span>{{
                salaries.find((item) => item.id === scope.row.expectedSalary)
                  .name || ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="education" label="学历">
            <template slot-scope="scope">
              <span>{{
                educations.find((item) => item.id === scope.row.education)
                  .name || ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="graduationTime" label="毕业时间">
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间">
            <template slot-scope="scope">
              {{ scope.row.updateTime | dateFMT }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="previewResume(scope.row)"
                size="small"
                >预览</el-button
              >
              <el-button
                type="primary"
                @click="handEdit(scope.row)"
                size="small"
                >编辑</el-button
              >
              <el-button type="danger" @click="handDel(scope.row)" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          hide-on-single-page
        >
        </el-pagination>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { regionData, CodeToText } from 'element-china-area-data';
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
import jsPDF from 'jspdf';
import { reqGetStudentInfoById } from '../StudentMng/api/studentApi';
import { reqBatchDelResume } from './api/ResumeMngApi';
export default {
  name: 'ResumeMng',
  data() {
    return {
      loading: false, // 遮罩层
      regionData: regionData,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      resumes: [], // 简历列表
      resumeQueryParam: {}, // 简历查询参数
      educations: [], // 学历列表
      salaries: [], // 期望薪资
      jobNames: [], // 职位名称
      // 时间选择快捷键
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    // 用户
    ...mapGetters(['name', 'description', 'loginId', 'avatar']),
    // 工作分类
    ...mapGetters('JobCategoryMng', ['categories', 'jobNameAndIdList']),
    // 数据字典
    ...mapGetters('DictMng', ['educationList', 'salaryList']),
    // 简历
    ...mapGetters('ResumeMng', ['resumeIPage', 'resumeList']),
    // 院系管理---专业编号与名称列表
    ...mapGetters('AcademyMng', ['majorListForIdAndName']),
  },
  watch: {
    // 薪水
    salaryList() {
      this.$set(this, 'salaries', this.salaryList);
    },
    // 学历
    educationList() {
      this.$set(this, 'educations', this.educationList);
    },
    //对应类别下的 工作名称
    jobNameAndIdList() {
      this.$set(this, 'jobNames', this.jobNameAndIdList);
    },
    resumeList() {
      this.$set(this, 'resumes', this.resumeList);
      this.loading = false;
    },
    resumeIPage() {
      if (this.resumeIPage.currentPage) {
        this.currentPage = this.resumeIPage.currentPage;
      }
      if (this.resumeIPage.pageSize) {
        this.pageSize = this.resumeIPage.pageSize;
      }
      if (this.resumeIPage.total) {
        this.total = this.resumeIPage.total;
      }
    },
  },
  mounted() {
    // 获取简历列表
    this.getResumeList();
    // 获取学历列表
    this.getEducationList();
    // 获取专业列表
    this.getMajorList();
    // 获取职位分类列表
    this.getCategories();
    // 获取薪水列表
    this.getSalaries();
  },
  methods: {
    // 学生简历的删除
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('ResumeMng/delResume', [row.id]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getResumeList();
        })
        .catch(() => {
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
        });
    },
    // 将简历信息到处为PDF
    exportPDF() {
      // 创建一个 jsPDF 对象
      const doc = new jsPDF();
      // 将需要导出的数据渲染到指定的 DOM 节点中
      const table = document.getElementById('export-table');

      // 将该节点转为 PDF 文件
      doc.addHTML(table, () => {
        // 下载 PDF 文件
        doc.save('export.pdf');
      });
    },

    // 预览简历
    previewResume(row) {
      // 根据学号查询学生头像
      reqGetStudentInfoById(row.studentId).then((res) => {
        // 学生没有被删除则显示学生头像，若被删除显示自带头像
        if (res.data) {
          row.avatar = res.data.studentInfo.avatar;
        }
        // 跳转至预览界面
        this.$router.push({
          name: 'resumetemplate',
          params: {
            isEdit: true,
            resumeRowInfo: row,
          },
        });
      });
    },
    // 编辑
    handEdit(row) {
      // 整理参数后，路由跳转
      // 将城市字符串编号转为数组
      let addressId = [];
      let arr = row.expectedCityId.split('-');
      arr.forEach((item) => {
        addressId.push(item);
      });
      this.$set(row, 'addressId', addressId);
      this.$router.push({
        name: 'resumeEdit',
        params: {
          isEdit: true,
          resumeRowInfo: row,
        },
      });
    },

    // 获取薪资列表
    async getSalaries() {
      // 查询薪资id
      let dict = await this.$store.dispatch('DictMng/getDictIdByName', '薪水');
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getSalaryListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的薪水编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },
    // 获取职位分类列表
    getCategories() {
      this.$store.dispatch('JobCategoryMng/getCategories');
    },
    // 获取学历列表
    async getEducationList() {
      // 查询学历id
      let dict = await this.$store.dispatch('DictMng/getDictIdByName', '学历');
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getEduListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的学历编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },
    // 获取专业编号与名称列表
    getMajorList() {
      this.$store.dispatch('AcademyMng/getMajorListForIdAndName');
    },

    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCompanyList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCompanyList();
    },
    // 重置查询参数
    resetResumeQueryParams() {
      this.resumeQueryParam = {};
    },
    // 刷新列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getResumeList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 查询简历列表
    getResumeList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('ResumeMng/getResumeList', params).then(() => {
        this.loading = false;
      });
    },

    // 条件查询
    async queryByCondition() {
      // 起始发布日期
      let updateTimeStart = '';
      // 截止发布日期
      let updateTimeEnd = '';
      if (this.resumeQueryParam.createTime) {
        if (this.resumeQueryParam.createTime[0]) {
          updateTimeStart = this.resumeQueryParam.updateTime[0];
        }
        if (this.resumeQueryParam.createTime[1]) {
          updateTimeEnd = this.resumeQueryParam.updateTime[1];
        }
      }
      // 初始化条件查询参数
      this.condition = {
        ...this.resumeQueryParam,
        updateTimeStart,
        updateTimeEnd,
      };
      await this.getResumeList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/* 表格扩展样式 */
// 表格扩展样式
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.function-button {
  margin-bottom: 10px;
}

// 折叠满样式 -- 搜索栏
.accordion {
  text-align: center;
  div {
    margin-bottom: 20px;
  }
  .queryBtn {
    // text-align: center;
  }
}
</style>
